/* 
************ READS ***************
 */
function get_content(url_read, url_write, domain_used, biov_domain, id){
    
    var q  = '{"query":[{'+
                '"name":null,'+
                '"board_members":[{"*":null,"optional":true}],'+
                '"companies_acquired":[{"*":null,"optional":true}],'+
                '"company_type":[{"*":null,"optional":true}],'+
                '"founded":{"*":null,"optional":true},'+
                //'"headquarters":{"*":}'
                '"headquarters":[{"optional":true,'+
                    '"*":[],'+
                    '"citytown" : {"optional":true,"id" : null,"guid":null, "name" : null},'+
                    '"state_province_region":{"optional":true,"id" : null,"guid":null, "name" : null},'+
                    '"street_address":[],'+//[{"id" : null,"name" : null}],'+
                    '"postal_code":{"optional":true,"id" : null, "guid":null, "name" : null}'+
                '}],'+
                '"industry":[{"*":null,"limit":10,"optional":true}],'+
                '"ticker_symbol":[{"*":null,"optional":true}],'+
                '"'+biov_domain+'science_or_technology_company/area_of_expertise":[{"*":null,"optional":true}],'+
                '"'+biov_domain+'science_or_technology_company/develops_treatments_for_disease":[{"*":null,"optional":true}],'+
                '"/common/topic/webpage":[{"*":null,"optional":true}],'+
                '"'+biov_domain+'science_or_technology_company/investment_round":[{"optional":true,'+
                    '"investment_round": {"optional":true,"id" : null,"name" : null},'+
                    '"amount_raised": null,'+
                    '"currency": {"optional":true,"id" : null,"name" : null},'+
                    '"date": null,'+
                    '"investors": [{"optional":true,"id" : null,"name" : null}],'+
                    '"web_reference" : null'+
                    '}],'+
                '"'+biov_domain+'bv_therapeutic/indication_or_disease":[{'+
                    '"disease":{"name":null, "id":null, "guid":null, "optional":true},'+
                    '"optional":true,'+
                    '"phase_of_development":null'+
                    '}],'+
                '"'+biov_domain+'science_or_technology_company/products":[{' +
                    '"*":null,' +
                    '"optional":true, ' +
                    '"sales":[{"*":null,"optional":true}],' +
                    '"developed_by":[{"name":null,"id":null,"optional":true}]' +
                    '}],'+
                '"thera:'+biov_domain+'science_or_technology_company/products":[{' +
                    '"type":"'+biov_domain+'bv_therapeutic",'+
                    '"name":null,'+
                    '"optional":true,'+
                    '"id":null,'+
                    '"guid":null,'+
                    '"'+biov_domain+'bv_therapeutic/indication_or_disease":' +
                        '[{' +
                            '"guid":null,'+
                            '"id":null,'+
                            '"name":null,'+
                            '"disease":{"name":null, "id":null, "guid":null, "optional":true},' +
                            '"optional":true,' +
                            '"phase_of_development":null' +
                        '}]'+
                    '}],'+
                '"guid":null,'+
                '"id" : "'+id+'",'+
                '"type":"/business/company"'+
                '}]}';

    perform_freebase_read(
        url_read,
        q,
        function (msg) {
                    
            var company = null;
            company = msg.result && msg.result[0] ? msg.result[0] : null;
            if (!company) return;
        
            var overviewText = new google.visualization.DataTable();
            overviewText.addColumn('string', '');
            overviewText.addColumn('string', '');
            overviewText.addRows(2);
            var overviewIndex = 0;
    
            if (company && company.name) {
                document.title = company.name;
                $('#title').text(company.name);
                __COMP__NAME__ = company.name;  
            }
            var name = company.name;
    
            var companyInfo = Object(); // Formatted verstion of the company information.
                    
            // ID's
            companyInfo.id = company.id;
            companyInfo.guid = company.guid;
            
            // Website
            var webpages = company["/common/topic/webpage"];
            var webpage = "";
            if (webpages && webpages.length > 0) {
                var w = webpages[0].uri;
                webpage = '<a href="' + w + '" target="_blank">' + company.name + '</a>';
            }
            overviewText.setCell(overviewIndex, 0, 'Webpage');
            overviewText.setCell(overviewIndex, 1, webpage);
            overviewIndex = overviewIndex + 1;
            companyInfo.webpages = webpages;
            
            // Company Type
            var companyType = (company.company_type.length > 0 ? company.company_type[0].name : "");
            //overviewText.setCell(overviewIndex, 0, 'Public or Private?');
            //overviewText.setCell(overviewIndex, 1, companyType);
            //overviewIndex = overviewIndex + 1;
            companyInfo.companyType = companyType;          
                        
            // Industry
            var industries = '';
            var industryArray = Array();
            for (var i in company.industry) {
                industries += company.industry[i].name + (i < company.industry.length - 1 ? ", " : "");
                industryArray[i] = company.industry[i].name;
            }
            //overviewText.setCell(overviewIndex, 0, 'Industries');
            //overviewText.setCell(overviewIndex, 1, industries);
            //overviewIndex = overviewIndex + 1;
            companyInfo.industries = company.industry;
    
            // Headquarters
            var headquarters = '';
            var streetAddress = '';
            var hqObject = Object();
            for (var i=0; i<1 && i<company.headquarters.length; i++) {
                var hq = company.headquarters[i];
                if(hq.street_address.length > 0){
                    headquarters += (typeof(hq.street_address) != "undefined" && hq.street_address != null ? hq.street_address[0] + "," : "" );
                }
                if(hq.citytown != null){
                    headquarters += (typeof(hq.citytown.name) != "undefined" && hq.citytown.name != null ? hq.citytown.name + "," : "" );               
                }
                if(hq.state_province_region != null){
                    headquarters += (typeof(hq.state_province_region.name) != "undefined" && hq.state_province_region.name != null ? hq.state_province_region.name + "," : "" );                
                }
                if(hq.postal_code != null ){
                    headquarters += (typeof(hq.postal_code.name) != "undefined" && hq.postal_code.name != null ? hq.postal_code.name : "" );                
                }
            }
            overviewText.setCell(overviewIndex, 0, 'Headquarters');
            overviewText.setCell(overviewIndex, 1, headquarters);
            overviewIndex = overviewIndex + 1;
            companyInfo.headquarters = company.headquarters;
            
            // Date Founded
            var founded = (company.founded && company.founded.value ? company.founded.value : "");           
            //overviewText.setCell(overviewIndex, 0, 'Date Founded');
            //overviewText.setCell(overviewIndex, 1, founded);
            //overviewIndex = overviewIndex + 1;
            companyInfo.founded = founded;

                        
            var overviewTable = new google.visualization.Table(document.getElementById('overview_div'));
            overviewTable.draw(overviewText, {width: 600, allowHtml: true});
            
            // Overview Text            
            var topic_domain = biov_domain+'science_or_technology_company';
            jsonp_totalblurb_freebase(domain_used, name, topic_domain, 500,
                function(m){
                    $("#thumb").attr('src','http://'+domain_used+'/api/trans/image_thumb'+m.result[0].image.id);
                },
                function(m){
                    $("#description").append($('<span>'+m.result.body+'</span>'));
                },
                function(m){
                    var test = 0;
                    
                }
            );
                        
            // Technologies:
            var technologies = company[biov_domain+'science_or_technology_company/area_of_expertise'];
            var techLinkInfo = Object();
            techLinkInfo.useLink = true;
            techLinkInfo.relDir = 'technology';
            createListWithHeader(technologies,'Technologies involved in:','tech_div', 3, techLinkInfo, false,-1);
            companyInfo.technologies = technologies;
            
            // Medical focus:
            var diseases = company[''+biov_domain+'science_or_technology_company/develops_treatments_for_disease'];
            var diseaseLinkInfo = Object();
            diseaseLinkInfo.useLink = true;
            diseaseLinkInfo.relDir = 'disease';
            createListWithHeader(diseases,'Medical focus:','diseases_div', 3, diseaseLinkInfo, true, -1)
            var diseaseNames = Array();
            for(var i in diseases){
                diseaseNames[i] = diseases[i].name;
            }
            companyInfo.diseases = diseases;
            
            // If publically traded, reate the stock ticker:
            
            //var tickerSymbols = company.ticker_symbol;
            //if(tickerSymbols.length > 0){
            //  var symb = tickerSymbols[0].ticker_symbol;
            //  createStockTicker(symb);            
            //}
             
            // Products
            var products = company[biov_domain+"science_or_technology_company/products"];
            createProductsInfo(products, domain_used, biov_domain, url_read, company.name);
            var productNames = Array();
            for(var i in products){
                productNames[i] = products[i].name;
            }
            companyInfo.products = products;
            companyInfo.productNames = productNames;        
            
            //Therapeutic pipeline
            var therapeutics = company['thera:'+biov_domain+'science_or_technology_company/products'];
            companyInfo.therapeutics = therapeutics;            
            
            // Financings
            var financingList = company[biov_domain+"science_or_technology_company/investment_round"];
            if(typeof(financingList)!='undefined'){
                createFinancingTable(financingList);
                companyInfo.investments = financingList;
            }                       
                        
            // Get the completion score for the company:
            var completion_score = calculateCompanyCompletion(companyInfo);
            var completion_string = '<input type="submit" id="completion_button" value="'+company.name+' is only '+completion_score+'% complete. Create an Account to Add More Content!"></input>';     
            var completion_string_login = '<div>'+company.name+' is  '+completion_score+'% complete. </div>';                   
            $("#completion_score").append(completion_string);
            $("#completion_button").bind("click", function(e){
                //location.href = "{% url registration.views.register %}";
                location.href = '/account/register'
            })
            $("#completion_score_login").append(completion_string_login);           

            // Set up the EDIT Page:
            create_edit_form(url_read, url_write, domain_used, biov_domain, companyInfo, name);
            
        },
        function(m){alert('test2')}
    );
}


function calculateCompanyCompletion(companyInfo){
    var score = 0;
    
    if(typeof(companyInfo.webpages) != 'undefined') {
        if(companyInfo.webpages.length>0){
            score += 10;
        }
    }
    if(typeof(companyInfo.companyType) != 'undefined'){
        if(companyInfo.companyType.length>0){
            score += 10;
        }
    }
    if(typeof(companyInfo.industries) != 'undefined'){
        if(companyInfo.industries.length>0){
            score += 10;
        }
    }
    if(typeof(companyInfo.headquarters) != 'undefined'){
        if(companyInfo.headquarters.length>0){
            score += 10;
        }
    }
    if(typeof(companyInfo.founded) != 'undefined'){
        if(companyInfo.founded.length>0){
            score += 10;
        }
    }
    if(typeof(companyInfo.technologies) != 'undefined'){
        if(companyInfo.technologies.length>0){
            score += 10;
        }
    }
    if(typeof(companyInfo.diseases)  != 'undefined'){
        if(companyInfo.diseases.length>0){
            score += 10;
        }
    }
    if(typeof(companyInfo.products) != 'undefined'){
        if(companyInfo.products.length>0){
            score += 10;
        }
    }
    if(typeof(companyInfo.investments) != 'undefined'){
        if(companyInfo.investments.length>0){
            score += 10;
        }
    }
    return score;
}

/**
 * Creates a table with financing data 
 */
function createFinancingTable(financingList){
    var financingTable = new google.visualization.DataTable();
    financingTable.addColumn('string', 'Financing Round');
    financingTable.addColumn('number', 'Amount (M)');
    financingTable.addColumn('string', 'Date');
    financingTable.addColumn('string', 'Investors');
    //financingTable.addColumn('string', 'More Info');
    financingTable.addRows(financingList.length);
          
    if(financingList.length > 0) {
        var h = '<br></br><h3>Financing</h3>';
        h = $(h);
        $("#financing_header").append(h);
            
        for (var i in financingList) {
            var financing = financingList[i];
            var amount = (financing.amount_raised != null ? financing.amount_raised : '0');
            var amountMil = amount/1000000;
            var round = '';
            if(financing.investment_round != null){
                round += (financing.investment_round.name != null ? financing.investment_round.name : "");
            }
            var date = (financing.date != null ? financing.date : "");
            var investors = financing.investors; 
            var investorString = '';
            for (var j in investors) {
                investorString += '<a href="/vcfirm' + investors[j].id  + '">' + investors[j].name + '</a>';
                investorString += ( j < investors.length-1 ? ', ' :"");
            }   

            var ref = financing.web_reference; 
            var refs_string = (ref != null ? '<a href="' + ref  + '" target="_blank">' + 'REF' + '</a>' : "");

            financingTable.setCell(parseFloat(i), 0, round);
            financingTable.setCell(parseFloat(i), 1, amountMil, amountMil.toString());
            financingTable.setCell(parseFloat(i), 2, date);
            financingTable.setCell(parseFloat(i), 3, investorString);
            //financingTable.setCell(parseFloat(i), 4, refs_string);
            
        }
        var financingTableDraw = new google.visualization.Table(document.getElementById('financing_div'));
        financingTableDraw.draw(financingTable, {allowHtml: true});         
    }
}   


// Creates tables for products, stratifying them into 'On the market' and 'Development'.
//
// Draws products on the market to the table: prodMarket_div
// Draws prodcuts in development to the table: prodDev_div

function createProductsInfo(products, domain_used, biov_domain, url_read, company_name){
    
    // Separate products into productTypes
    var productObj = getProductTypes(products, "");
    
    if(productObj.products.length > 0){
        var h_ProdMarket = '<h2>Products on the Market</h2>';
        h_ProdMarket = $(h_ProdMarket)
        $("#h_ProdMarket").append(h_ProdMarket); 
        var h_ProdDev = '<h2>Products in Development</h2>';
        h_ProdDev = $(h_ProdDev)
        $("#h_ProdDiv").append(h_ProdDev); 
        
        var marketCols = [0,1,3,4,5];
        var devCols = [0,1,3,4];
        barOptions = Object();
        barOptions.salesByCompanies = false;
        barOptions.salesByProducts = true;
        createProductTable(productObj.products, domain_used, biov_domain, marketCols, devCols, barOptions);
    }
    if(productObj.therapeutics.length > 0){
        var h_TherMarket = '<h2><span>Therapeutics on the Market</span></h2>';
        h_TherMarket = $(h_TherMarket)
        $("#h_TherMarket").append(h_TherMarket); 
        var h_TherMarket = '<h2><span>Therapeutics in Development</span></h2>';
        h_TherMarket = $(h_TherMarket)
        $("#h_TherDiv").append(h_TherMarket); 
        // Need to query for therapeutic properties.
        var qThera = '{"query":[{"'+biov_domain+'bv_therapeutic/biomolecule_or_target":[],"'+biov_domain+'bv_therapeutic/indication_or_disease":[{"disease":[{"name":null, "id":null}],"optional":true,"phase_of_development":null}],"a:type":[],"brand_name":[],"developed_by":"'+company_name+'","a:developed_by":[{"name":null, "id":null}],"name":null,"id":null,"sales":[{"amount":null,"area":null,"optional":true,"year":null,"company_reporting":null}],"stage_of_development":null,"technology_involved":[],"type":"'+biov_domain+'product"}]}'; 
        //var q = '{"query":[{"developed_by":"'+name+'","name":null,"type":"/user/bioventurist/default_domain/product","brand_name":[],"a:type":[],"stage_of_development":null,"sales":[{"year":null,"amount":null,"area":null, "optional":true}]}]}';
        
        //createTherapeuticTable(productObj.therapeutics, domain_used);
        perform_freebase_read(
            url_read,
            qThera,
            function (msg2) {
                var therapeutics = null;
                therapeutics = msg2.result;
                if(therapeutics.length > 0){
                    var marketCols = [0,1,2,4];
                    var devCols = [0,1,2];
                    var barOptions = Object();
                    barOptions.salesByCompanies = false;
                    barOptions.salesByProducts = true;
                    var companyOptions = Object();
                    companyOptions.specifyCompany = true;
                    companyOptions.companyName = company_name;
                    createTherapeuticsTable(therapeutics, domain_used, biov_domain, marketCols, devCols, barOptions, false, companyOptions);        
                }
            },
            function(m){}
        );
    }
}

function createStockTicker(symb){
    var width = 450;
    var height = 245;

    var s = ''+
    '<h3>Stock Data</h3>'+
    '<object id="ticker_id" width="'+width+'" height="'+height+'"  codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab#9,0,28" classid="clsid:ticker_id">'+
        '<param name="movie" value="http://charts.wikinvest.com/WikiChartMini.swf"></param>'+
        '<param name="allowFullScreen" value="false"></param><param name="allowScriptAccess" value="always"></param>'+
        '<param name="flashvars" value="ticker='+symb+'&startDate=30-06-2008&endDate=30-12-2008&rollingDate=&showAnnotations=true&liveQuote=true"></param>'+
        '<embed src="http://charts.wikinvest.com/WikiChartMini.swf" type="application/x-shockwave-flash"  allowfullscreen="true"  allowScriptAccess="always"  width="'+width+'" height="'+height+'" flashvars="ticker='+symb+'&startDate=30-06-2008&endDate=30-12-2008&rollingDate=&showAnnotations=true&liveQuote=true"></embed>'+
    '</object>'+
    '<div style="font-size:9px;text-align:right;width:'+width+'px;font-family:Verdana"></div>'+
    '<br></br>';
    $("#stockTicker").append(s); 


}

/**************************************** 
* Legacy code that we may want to use:
 
*/

